const { exec } = require('child_process')
const moment = require('moment')
const FIX_PATTERN = /\[fix (.*?)][:：]?\s*(.*)/

const command = `git log --since="midnight" --until="23:59" --pretty=format:"<&& %cd &&> <&& %s &&>" --date=format:"%Y-%m-%d %H:%M:%S"`

moment.locale('zh_cn')

exec(command, (error, stdout, stderr) => {
  if (stdout) {
    try {
      const context = stdout.split('\n')
      const commits = commentator(context)

      const collaborative = new Map()

      commits.forEach(lines => {
        const [time, commit] = lines
        const match = FIX_PATTERN.exec(commit)
        if (match) {
          const [_, context, url] = match
          if (context) {
            const URL_PATTERN = /^https?:\/\/.+/
            collaborative.set(context, {
              context,
              url: URL_PATTERN.test(url) ? url : null,
              time: moment(time).fromNow()
            })
          }
        }
      })

      withdrawCommitForWechat(collaborative)

      process.exit(0)
    } catch (e) {
      console.log(e)
      process.exit(0)
    }
  }
})

function commentator(commits = []) {
  if (Array.isArray(commits) && commits.length > 0) {
    const pattern = /<&& (.*?) &&>/g
    return commits.map(line => {
      return [...line.matchAll(pattern)].map(match => match[1].replace(/["']/g, ''))
    })
  }
}

function withdrawCommitForWechat(commits) {
  if (commits.size > 0) {
    let publish = ""
    commits.forEach(({ context, url, time }) => {
      const commit = url ? `[${context.trim()}](${url})  (${time}) \n` : `<font color=\'comment\'>${context.trim()}  (${time})</font> \n`
      publish+=`${commit}`
    })

    console.log(publish)
  }
}
